<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)" />

    <van-search show-action placeholder="请输入搜索关键词" clearable v-model="value" @search="onSearch(value.trim())">
      <template #action>
        <div @click="onSearch(value.trim())">搜索</div>
      </template>
    </van-search>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="searchHistory.length > 0 ">
      <div class="title">
        <span>最近搜索</span>
        <van-icon @click="clear" name="delete-o" size="16" />
      </div>
      <div class="list">
        <div class="list-item" @click="onSearch(item.trim())" v-for="(item, index) in searchHistory" :key="index">{{item}}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { getHistory, setHistory } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchHistory: getHistory(),
      value: ''
    }
  },
  methods: {
    onSearch (value) {
      if (!value) return
      // console.log(value)
      // 如果搜索历史中没有当前搜索的关键词 则追加到搜索历史中
      const searchHistory = this.searchHistory
      // if (!this.searchHistory.includes(value)) {
      //   this.searchHistory.unshift(value)
      // } else {
      //   // 如果搜索历史中有当前搜索的关键词 则删除当前搜索的关键词 并追加到搜索历史中
      //   this.searchHistory.splice(this.searchHistory.indexOf(value), 1)
      //   this.searchHistory.unshift(value)
      // }
      searchHistory.includes(value) ? searchHistory.splice(searchHistory.indexOf(value), 1) && searchHistory.unshift(value) : searchHistory.unshift(value)
      setHistory(searchHistory)
      // 跳转到搜索列表页
      this.$router.push('/searchlist?search=' + value) // 模板字符串 和 字符串拼接 均可实现跳转
    },
    // 清空搜索历史
    clear () {
      this.searchHistory = []
      setHistory([])
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  .searchBtn {
    background-color: #fa2209;
    color: #fff;
  }
  ::v-deep .van-search__action {
    background-color: #c21401;
    color: #fff;
    padding: 0 20px;
    border-radius: 0 5px 5px 0;
    margin-right: 10px;
  }
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }
  .list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }
  .list-item {
    width: 30%;
    text-align: center;
    padding: 7px;
    line-height: 15px;
    border-radius: 50px;
    background: #fff;
    font-size: 13px;
    border: 1px solid #efefef;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
}
</style>
